/**
 * 接收前端消息的类
 * @class ReceiveMessage
 */
class ReceiveMessage {
  /**
   * @private
   * @type {Object<string|number, Function[]>}
   */
  eventObj = {};

  constructor() {
    window.addEventListener("message", (ev) => {
      if (this.eventObj[ev.data.type]) {
        // 调用所有注册的监听器
        this.eventObj[ev.data.type].forEach((callback) => {
          try {
            callback(ev.data);
          } catch (error) {
            console.error("Error in event listener:", error);
          }
        });
      }
    });
  }

  /**
   * 添加事件监听器
   * @function addListener
   * @param {string} eventKey - 事件的键名，用于标识事件类型，ReceiveMessageType中的枚举值
   * @param {Function} callback - 事件触发时调用的回调函数，接收一个消息数据参数
   * @returns {void}
   */
  addListener(eventKey, callback) {
    if (!this.eventObj[eventKey]) {
      this.eventObj[eventKey] = [];
    }
    this.eventObj[eventKey].push(callback);
  }
}

// 创建单例实例
const receiveMessage = new ReceiveMessage();
export default receiveMessage;
